package com.quirqy.service;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;


import com.quirqy.model.Person;
import com.quirqy.persistence.EMF;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.persistence.EntityManager; 

@Controller
public class RestPutService 
{

	@RequestMapping( value = "people/{id}",method = RequestMethod.PUT )
	@ResponseStatus( HttpStatus.OK )
	public final Person set( @PathVariable( "id" ) final Long id, @RequestBody final Person p )
	{
		EntityManager em = EMF.get().createEntityManager();
		Person pOrig = em.find(Person.class, id);
		if (pOrig != null)
		{
			//TODO: should only set properties if provided
			pOrig.setEmail(p.getEmail());
			pOrig.setName(p.getName());
			pOrig.setPassword(p.getPassword());

			em.getTransaction().begin();
			em.merge(pOrig); 
			em.getTransaction().commit();
			em.close();
		}
		return pOrig;
	}
}
